package com.bdqn.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.bdqn.realm.UserRealm;
import lombok.Builder;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Shiro配置类
 */
@Configuration
public class ShiroConfig {
    @Bean
    public DefaultWebSecurityManager     securityManager(Realm realm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }
    @Bean
    public Realm realm(){
        UserRealm realm=new UserRealm();
        HashedCredentialsMatcher matcher=new HashedCredentialsMatcher("md5");
        matcher.setHashIterations(9);
        realm.setCredentialsMatcher(matcher);
        return realm;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean=new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);//设置过滤规则
        Map<String,String> map = new HashMap<>();
        //不需要拦截的
        map.put("/css/**", "anon");
        map.put("/css1/**", "anon");
        map.put("/images/**", "anon");
        map.put("/js/**", "anon");
        map.put("/fonts/**", "anon");
        map.put("/", "anon");
        map.put("/user/login", "anon");
        //需要拦截
        map.put("/**", "authc");
        filterFactoryBean.setFilterChainDefinitionMap(map);
        //设置默认拦截后的跳转页面
        filterFactoryBean.setLoginUrl("/");
        return filterFactoryBean;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
